package aaa.controller;

import aaa.pojo.Books;
import aaa.service.AccountService;
import aaa.service.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import aaa.service.BookService;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
    @Autowired
    private AccountService accountService;

    @RequestMapping("/allcount")
    public String count(Model model) {
// 调用服务层查询所有书籍
        try {
            accountService.transfer("1", "2", 3.0);
            System.out.println("转账成功！");
        } catch (Exception e) {
            System.out.println("转账失败：" + e.getMessage()); // 捕获事务回滚后的异常
        }
        return "account";
    }
    /**
     * 方法1.查询全部书籍
     *
     * @param model 用于向视图传递数据模型
     * @return 返回视图名称"allBook" ，对应JSP页面
     */
    @RequestMapping("/allBook")
    public String list(Model model) {
        //调用服务层查询所有书籍
        List<Books> list = bookService.findall();
        //将查询结果存入模型，键为“list”，视图层可通过${list}
        model.addAttribute("list", list);
        return "allBook";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        //空方法直接跳转视图，无业务逻辑
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        System.out.println(books);
        bookService.addbook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
        System.out.println(id);
        Books books = bookService.findbook(id);
        model.addAttribute(books);
        System.out.println(books);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Model model, Books book) {
        System.out.println(book);
        bookService.updatebook(book);
        Books updateBook = bookService.findbook(book.getId());
        model.addAttribute("books", updateBook);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/del/{id}")
    public String deleteBook(@PathVariable("id") int id) {
        bookService.deletebook(id);
        return "redirect:/book/allBook";
    }
}
